const ACCESS_TOKEN = 'access-token'
const ACCESS_OWNER_TOKEN = 'access-owner-token'
let defaultExpireTime = 0
// token过期时间系数
const factor_expire = 0.8

module.exports = {
  /**
   * @param 键 key
   * @param 值 value
   * @param 过期时间(单位：秒) expire
   */
  set (key, value, expire, storage = localStorage) {
    storage.setItem(key, JSON.stringify({
      value,
      expire: expire ? new Date().getTime() + parseInt(expire) * 1000 : null
    }))
  },
  /**
   * @param 键 key
   * @param 如果过期是否删除该缓存 removeIfexpire
   * @returns
   */
  get (key, removeIfExpire = false, storage = localStorage) {
    const data = JSON.parse(storage.getItem(key))
    if (data) {
      if (removeIfExpire && data.expire && data.expire / factor_expire < new Date().getTime()) {
        this.remove(key)
      } else {
        return data.value
      }
    }
    return null
  },
  remove (key, storage = localStorage) {
    storage.removeItem(key)
  },
  clear (storage = localStorage) {
    storage.clear()
  },
  /**
   * 获取过期时间
   * @param {*} key
   * @param {*} storage
   * @returns  -1 - 已失效，0 - 即将失效，其他 - 即将失效时间
   */
  expireTime (key, storage = localStorage) {
    const data = JSON.parse(storage.getItem(key))
    if (data && data.expire) {
      const now = new Date().getTime()
      if (data.expire / factor_expire < now) {
        // 已经失效
        return -1
      }
      if (data.expire / factor_expire > now && data.expire < now) {
        // 即将失效
        return 0
      }
      return (data.expire - now) / 1000
    }
    return Number.MAX_SAFE_INTEGER
  },
  removeToken (storage = localStorage) {
    this.remove(ACCESS_TOKEN, storage)
  },
  setToken (token, validTime, storage = localStorage) {
    this.set(ACCESS_TOKEN, token, validTime * factor_expire, storage)
  },
  getToken (storage = localStorage) {
    let token = this.get(ACCESS_TOKEN, false, storage)
    const expireTime = this.expireTime(ACCESS_TOKEN, storage)
    if (!token) {
      return null
    }
    token = { value: token }
    token.expired = expireTime
    // if (seconds <= 0) {
    //   token.expire = -1
    // } else if (defaultExpireTime <= seconds) {
    //   token.expire = 1
    // } else if (defaultExpireTime > seconds) {
    //   token.expire = 0
    // }
    return token
  },
  setOwnerToken (token, validTime, storage = localStorage) {
    this.set(ACCESS_OWNER_TOKEN, token, validTime * factor_expire, storage)
  },
  getOwnerToken (storage = localStorage) {
    let token = this.get(ACCESS_OWNER_TOKEN, false, storage)
    const expireTime = this.expireTime(ACCESS_OWNER_TOKEN, storage)
    if (!token) {
      return null
    }
    token = { value: token }
    token.expired = expireTime
    return token
  },
  removeOwnerToken (storage = localStorage) {
    this.remove(ACCESS_OWNER_TOKEN, storage)
  }
}
